package org.redr.canvas;

import java.util.ArrayList;
import java.util.List;

public class RedRSignalManager {
	
	
	private static List<LinkPair> links = new ArrayList<LinkPair>();
	
	/**
	 * This function sends data from the outwidget specified by owid through
	 * the signal specified by id.  The data will be extracted from the RRW
	 * instance and sent to the standard data receiver in the inWidget.
	 * The inWidget is specified by the iwid parameter.
	 * @param owid
	 * @param iwid
	 * @param id
	 */
	public static void send(String wid, String iwid, String id, String iid)
	{
		/*
		 * set the data for the output socket of widget wid signal id, to signal
		 */
		
		RRW outWidget = RedRObjects.getWidgetInstanceByID(wid);
		RRW inWidget = RedRObjects.getWidgetInstanceByID(iwid);
		
		// we do a check here to make sure that neither of the widget 
		// id's are not actually held by a widget, this is really an error
		// and in future renditions this should be changed to 
		// raise an Exception...  TODO
		if (outWidget == null || inWidget == null) return;
		
		// developers should note that the signal might be null.
		SignalClass signal = outWidget.getSignalDataBySocket(id);
		
		// we wrap this in a try so that errors in widgets, which are developed
		// by others does not crash the core.  
		try{
			inWidget.dataInput(iid, signal, wid);
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * Calls a send for all attached connections.  This will call the send
	 * command of RedRSignalManager recursively for each connection.
	 * This function should be called when new data is available for the 
	 * widget, when a send command is called.
	 * 
	 * @param wid
	 * @param sid
	 */
	public static void sendData(String wid, String sid){
		// collect all of the input sockets that connect to the 
		// output that we specify here
		List<InputSocket> connectedSockets = new ArrayList<InputSocket>();
		for (LinkPair lp : links){
			InputSocket is = lp.getInput();
			OutputSocket os = lp.getOutput();
			if (os.getWidgetId().equals(wid) || os.getSignalId().equals(sid))
				connectedSockets.add(is);
		}
		
		// now loop over the connectedSockets and perform the send
		for (InputSocket is : connectedSockets){
			RedRLog.log(RedRLog.core, RedRLog.info, "Sending data between widgets");
			send(wid, is.getWidgetId(), sid, is.getSignalId());
		}
	}

	public static void addInput(InputSocket ins) {
		// TODO Auto-generated method stub
		
	}

	public static void addOutput(OutputSocket outs) {
		// TODO Auto-generated method stub
		
	}

	

	
	
	/*
	 * Functions to connect signals.
	 */
	
	
	/*
	 * Functions to send signals.
	 */

}
